package com.cysnake.quitsmoke.common.dao;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class BaseDao {

	private static final String TAG = "BaseDao";

	private static final String DATABASE_NAME = "quitsmoke";
	private static final int DATABASE_VERSION = 1;

	public class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			String COST_CREATE = "create table " + CostDao.TABLE_NAME + " ("
					+ CostDao.KEY_ID + " integer primary key autoincrement,"
					+ CostDao.KEY_NAME + " text," 
					+ CostDao.KEY_COSTNUM+ " number(6,2)," 
					+ CostDao.KEY_BUYTIME + " text)";
			Log.i(TAG, COST_CREATE);
			db.execSQL(COST_CREATE);

			String HiSTORY_CREATE = "create table " + HistoryDao.TABLE_NAME+ " (" 
					+ HistoryDao.KEY_ID + " integer primary key autoincrement, "
					+ HistoryDao.KEY_SMOKETIME + " text)";
			Log.i(TAG, HiSTORY_CREATE);
			db.execSQL(HiSTORY_CREATE);

			String PLAN_CREATE = "create table " + PlanDao.TABLE_NAME + " ("
					+ PlanDao.KEY_ID + " integer primary key , "
					+ PlanDao.KEY_STARTTIME + " text," 
					+ PlanDao.KEY_ENDTIME+ " text,"
					+PlanDao.KEY_SMOKENUM+ " integer)";
			Log.i(TAG, PLAN_CREATE);
			db.execSQL(PLAN_CREATE);
			
			String VIEW_HISTORY_CREATE="create view "+ViewHistoryDao.TABLE_NAME
					+" as select count(["+HistoryDao.KEY_ID+"]) as " +ViewHistoryDao.KEY_COUNT+" , "
					+"["+HistoryDao.KEY_SMOKETIME+"]"+" as "+ViewHistoryDao.KEY_DATE
					+" from "+HistoryDao.TABLE_NAME
					+" group by "+"["+HistoryDao.KEY_SMOKETIME+"]";
			Log.i(TAG, VIEW_HISTORY_CREATE);
			db.execSQL(VIEW_HISTORY_CREATE);

		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + CostDao.TABLE_NAME + ";");
			db.execSQL("DROP TABLE IF EXISTS " + HistoryDao.TABLE_NAME + ";");
			db.execSQL("DROP TABLE IF EXISTS " + PlanDao.TABLE_NAME + ";");
			db.execSQL("DROP VIEW IF EXISTS " + ViewHistoryDao.TABLE_NAME + ";");
			onCreate(db);
		}

	}
}
